package com.mind.ridge.service.backend.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mind.ridge.dto.backend.SetmealDishDto;
import com.mind.ridge.mapper.backend.SetmealMapper;
import com.mind.ridge.pojo.backend.Category;
import com.mind.ridge.pojo.backend.Setmeal;
import com.mind.ridge.pojo.backend.SetmealDish;
import com.mind.ridge.service.backend.CategoryService;
import com.mind.ridge.service.backend.SetmealDishService;
import com.mind.ridge.service.backend.SetmealService;
import com.mind.ridge.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mind
 */
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Resource
    private CategoryService categoryService;

    @Resource
    private SetmealDishService setmealDishService;

    @Override
    public R<IPage> pageSet(int page, int pageSize, String name) {

        //分页查询套餐
        IPage<Setmeal> setPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //根据套餐名模糊查询
        lqw.like(Strings.isNotBlank(name), Setmeal::getName, name);

        //查询
        this.page(setPage, lqw);

        //创建一个新的page对象，将 原来的page copy到新的page构成新的组成对象
        IPage<SetmealDishDto> dtoPage = new Page<>();
        BeanUtils.copyProperties(setPage, dtoPage, "records");

        //获取原来获取到的所有数据
        List<Setmeal> records = setPage.getRecords();

        //通过stream流将对应的分类id所对应的分类名封装到dto中
        List<SetmealDishDto> dtoList = records.stream().map((item) -> {
            SetmealDishDto dto = new SetmealDishDto();
            BeanUtils.copyProperties(item, dto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dto.setCategoryName(category.getName());
            return dto;
        }).collect(Collectors.toList());

        //最后将映射后的list 设置到dtoPage的record中即可
        dtoPage.setRecords(dtoList);
        return R.success(dtoPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<String> add(SetmealDishDto dto) {
        if (dto == null) {
            return R.error("空值");
        }

        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(dto, setmeal);
        this.save(setmeal);

        List<SetmealDish> setmealDishes = dto.getSetmealDishes();

        setmealDishes = setmealDishes.stream().map((item) -> {
            log.info(setmeal.getId().toString());
            item.setSetmealId(setmeal.getId());
            return item;
        }).collect(Collectors.toList());


        setmealDishService.saveBatch(setmealDishes);
        return R.success("success");
    }

    @Override
    public R<String> alterStatus(Long[] ids, int status) {
        if (ids == null) {
            return R.error("ERROR");
        }

        List<Setmeal> list = new ArrayList<>();
        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            list.add(setmeal);
        }

        return this.updateBatchById(list) ? R.success("修改成功") : R.error("该数据或已被删除");
    }

    @Override
    public R<String> delete(Long[] ids) {
        if (ids == null) {
            return R.error("ERROR");
        }
        List<Long> list = Arrays.asList(ids);
        return this.removeBatchByIds(list) ? R.success("删除成功") : R.error("该记录或已被删除");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R<SetmealDishDto> echoInfo(long id) {
        //通过id查询并获取setmeal对象
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getId, id);
        Setmeal setmeal = this.getOne(wrapper);

        //创建dto
        SetmealDishDto dto = new SetmealDishDto();

        //将setmeal的数据拷贝到dto中
        BeanUtils.copyProperties(setmeal, dto);

        //查询套餐菜品
        LambdaQueryWrapper<SetmealDish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(dishWrapper);

        //将套餐菜品存入dto中
        dto.setSetmealDishes(list);

        //返回dto对象
        return R.success(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<String> updateModify(SetmealDishDto dto) {
        if (dto == null) {
            return R.error("ERROR");
        }

        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(dto, setmeal);
        this.updateById(setmeal);

        List<SetmealDish> dishes = dto.getSetmealDishes();

        for (SetmealDish dish : dishes) {
            if (dish.getSetmealId() == null) {
                dish.setSetmealId(setmeal.getId());
                setmealDishService.save(dish);
            } else {
                LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SetmealDish::getSetmealId, setmeal.getId());
                setmealDishService.update(dish, wrapper);
            }
        }

        return R.success("修改成功");
    }

    @Override
    public R<List<SetmealDishDto>> setmealList(Long categoryId, Integer status) {
        if (categoryId == null) {
            return R.error("ERROR");
        }
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getCategoryId, categoryId)
                .eq(status != null, Setmeal::getStatus, status);
        List<Setmeal> list = this.list(lqw);

        List<SetmealDishDto> dtoList =  list.stream().map((item)->{
            SetmealDishDto dto = new SetmealDishDto();
            BeanUtils.copyProperties(item,dto);
            LambdaQueryWrapper<SetmealDish> dishWrapper = new LambdaQueryWrapper<>();
            dishWrapper.eq(SetmealDish::getSetmealId,item.getId());
            List<SetmealDish> dishes = setmealDishService.list(dishWrapper);
            dto.setSetmealDishes(dishes);
            return dto;
        }).collect(Collectors.toList());

        return R.success(dtoList);
    }
}
